package com.gxa.p2p.controller;

import com.gxa.p2p.businessExceptionCode.ErrorCode;
import com.gxa.p2p.exception.BusinessException;
import com.gxa.p2p.util.MapUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

// @ControllerAdvice 定义异常控制器
@CrossOrigin
@ControllerAdvice
@ResponseBody
@Log4j2
public class ExceptionController {
  /*
   @ExceptionHandler 异常处理器
    @ExceptionHandler({Throwable.class})  捕获所有异常

  */
  @ExceptionHandler(Throwable.class)
  public Map<String, Object> exceptionHandle(Throwable throwable) {
    /*
       若是业务类型得异常：给前端code/desc,给用户看
       若是系统异常,错误可以给前端提示,具体内容前端不需要知道
           将信息错误记录到日志
    */
    MapUtil mapUtil = new MapUtil();
    if (throwable instanceof BusinessException) {
      System.out.println("出现业务异常!");
      ErrorCode errorCode = ((BusinessException) throwable).getErrorCode();

      mapUtil.setCode(errorCode.getCode());
      mapUtil.setMsg("发生业务异常!");
    } else {
      System.out.println("出现系统异常,请查看tomcat根目录下appLogs文件夹里的日志文件");
      log.info("-----------------begin-----------------");
      log.info(throwable.getMessage());
      log.info("-----------------end-----------------");
      mapUtil.setCode(500);
      mapUtil.setMsg("后台未知异常!");
    }
    return mapUtil.getMap();
  }
}
